﻿using OpcUaHelper;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
using System.Windows;

namespace FPSO.HMI.Utils
{
    internal class AuthUtil
    {
        /// <summary>
        /// 鉴权操作
        /// </summary>
        /// <returns>管理员：true，其它：false</returns>
        public static bool IsHasPermission()
        {
            //DEBUG暂时不启用用户权限管理
            //return true;
            try
            {
                if (((App)Application.Current).LoginStatus == 1)
                {
                    return true;
                }
                else
                {
                    MessageBox.Show("当前为普通用户：" + GetLoginUser() + "，无操作权限！", "权限校验失败");
                    return false;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("未知错误：" + ex.Message.ToString(), "权限校验失败");
                return false;
            }

        }

        /// <summary>
        /// 设置全局登录状态，0：普通用户，1：管理员用户
        /// </summary>
        /// <param name="type">状态码</param>
        public static void SetLoginStatus(int type)
        {
            ((App)Application.Current).LoginStatus = type;
        }

        /// <summary>
        /// 设置当前登录用户
        /// </summary>
        /// <param name="type">用户名</param>
        public static void SetLoginUser(string username)
        {
            ((App)Application.Current).LoginUser = username;
        }

        /// <summary>
        /// 获取当前登录用户
        /// </summary>
        /// <returns>用户名</returns>
        public static string GetLoginUser()
        {
            return ((App)Application.Current).LoginUser;
        }

		//AES加密和解密方法应用实例
		//string original = "Hello, World!";
		//string encrypted = AuthUtil.EncryptStringToBytes_Aes(original);
		//string decrypted = AuthUtil.DecryptStringFromBytes_Aes(encrypted);

		//Console.WriteLine($"Original: {original}");  
		//Console.WriteLine($"Encrypted: {encrypted}");  
		//Console.WriteLine($"Decrypted: {decrypted}");

		// 生成随机的AES密钥（Key）
		// 
		public static byte[] GenerateAesKey(int keySize = 256)
		{
			using (Aes aesAlg = Aes.Create())
			{
				aesAlg.KeySize = keySize; // 可以是128, 192, 或 256  
				aesAlg.GenerateKey();
				return aesAlg.Key;
			}
		}

		// 生成随机的AES初始化向量（IV）  
		public static byte[] GenerateAesIv(int blockSize = 128)
		{
			// 对于AES，块大小始终是128位（16字节），因此这里的blockSize参数实际上是多余的，但为了保持一致性和未来的兼容性，我们还是接受它  
			byte[] iv = new byte[blockSize / 8]; // 字节长度 = 位长度 / 8  
			using (RandomNumberGenerator rng = RandomNumberGenerator.Create())
			{
				rng.GetBytes(iv);
			}
			return iv;
		}

		private static readonly byte[] Key = Encoding.UTF8.GetBytes("20240825202408252024082520240825");
		private static readonly byte[] Iv = new byte[16]; // 通常IV也是随机生成的，但这里为了简化示例而硬编码  

		//private static readonly byte[] Key = GenerateAesKey(256); // 生成256位的AES密钥  
		//private static readonly byte[] Iv = GenerateAesIv(); // 生成128位的AES初始化向量（即16字节）
		public static string EncryptStringToBytes_Aes(string plainText)
		{
			if (plainText == null || plainText.Length <= 0)
				throw new ArgumentNullException("plainText");

			byte[] encrypted;

			// 创建AES实例  
			using (Aes aesAlg = Aes.Create())
			{
				aesAlg.Key = Key;
				aesAlg.IV = Iv;

				// 创建加密器  
				ICryptoTransform encryptor = aesAlg.CreateEncryptor(aesAlg.Key, aesAlg.IV);

				// 创建流来加密数据  
				using (MemoryStream msEncrypt = new MemoryStream())
				{
					using (CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write))
					{
						using (StreamWriter swEncrypt = new StreamWriter(csEncrypt))
						{
							// 写入数据到加密流  
							swEncrypt.Write(plainText);
						}
						encrypted = msEncrypt.ToArray();
					}
				}
			}

			// 返回Base64编码的加密字符串  
			return Convert.ToBase64String(encrypted);
		}

		public static string DecryptStringFromBytes_Aes(string cipherText)
		{
			if (cipherText == null || cipherText.Length <= 0)
				throw new ArgumentNullException("cipherText");

			byte[] cipherBytes = Convert.FromBase64String(cipherText);

			// 创建AES实例  
			using (Aes aesAlg = Aes.Create())
			{
				aesAlg.Key = Key;
				aesAlg.IV = Iv;

				// 创建解密器  
				ICryptoTransform decryptor = aesAlg.CreateDecryptor(aesAlg.Key, aesAlg.IV);

				// 创建流来解密数据  
				using (MemoryStream msDecrypt = new MemoryStream(cipherBytes))
				{
					using (CryptoStream csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read))
					{
						using (StreamReader srDecrypt = new StreamReader(csDecrypt))
						{
							// 读取解密流并返回字符串  
							return srDecrypt.ReadToEnd();
						}
					}
				}
			}
		}
	}
}
